package com.ysy.logistics.controller.system;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ysy.common.resp.ResultData;
import com.ysy.common.resp.ReturnCodeEnum;
import com.ysy.logistics.entities.system.RoleNotice;
import com.ysy.logistics.entities.system.SysRole;
import com.ysy.logistics.entities.system.UserRole;
import com.ysy.logistics.myannotation.OperateLog;
import com.ysy.logistics.myenum.NoticeType;
import com.ysy.logistics.service.system.RoleNoticeService;
import com.ysy.logistics.service.system.SysRoleService;
import com.ysy.logistics.service.system.UserRoleService;
import com.ysy.logistics.service.system.RoleMenuService;
import com.ysy.logistics.util.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/13 9:54
 **/
@Slf4j
@RestController
@RequestMapping(value = "/sysRole",name = "角色")
@Tag(name = "角色管理",description = "role表的CRUD")
@CrossOrigin
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private RoleMenuService roleMenuService;
    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleNoticeService roleNoticeService;

    @PostMapping("/save")
    @Operation(summary = "保存单个角色",description = "保存单个角色")
    @OperateLog("保存角色")
    public ResultData saveSingle(@RequestBody SysRole sysRole){
        //查询角色编码
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper();
        lqw.select().eq(SysRole::getCode,sysRole.getCode());
        if (sysRoleService.exists(lqw)){
            return ResultData.fail("角色编码已存在");
        }
        log.debug("保存角色：{}",sysRole);
        return sysRoleService.save(sysRole)?ResultData.success():ResultData.fail(ReturnCodeEnum.RC500);
    }

    @PostMapping("/updateById")
    @Operation(summary = "修改单个角色",description = "通过ID修改角色信息")
    @OperateLog("修改角色")
    public ResultData updateSingle(@RequestBody SysRole sysRole){
        log.debug("修改角色：{}",sysRole);
        if (sysRole.getId()==null) {
            return ResultData.fail(ReturnCodeEnum.NOT_LOGIN);
        }
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper();
        lqw.select().eq(SysRole::getCode,sysRole.getCode()).ne(SysRole::getId,sysRole.getId());
        if (sysRoleService.exists(lqw)){
            return ResultData.fail("角色编码已存在");
        }
        return sysRoleService.updateById(sysRole)?ResultData.success():ResultData.fail(ReturnCodeEnum.RC500);
    }

    @PostMapping("/list")
    @Operation(summary = "分页查询",description = "分页查询")
    @OperateLog("查询角色列表")
    public ResultData list(@RequestBody PageInfo<SysRole> pageInfo){
        log.debug("分页查询角色："+pageInfo);
        return ResultData.success(sysRoleService.listByPage(pageInfo));
    }

    @PostMapping("/savePermisson/{id}")
    @Operation(summary = "保存权限",description = "保存权限")
    @OperateLog("角色授权")
    public ResultData savePermisson(@PathVariable("id") String id,@RequestBody Integer[] permissionIds){
        log.debug("保存权限：{}",permissionIds);
        //角色是否存在
        if (id == null || !sysRoleService.exists(new LambdaQueryWrapper<SysRole>().eq(SysRole::getId,id))){
            return ResultData.fail("角色不存在");
        }
        //删除原来角色的权限
        roleMenuService.deleteByRoleId(id);
        //添加新的权限
        roleMenuService.addRoleMenu(id,permissionIds);
        return ResultData.success();
    }

    @GetMapping("/delete/{id}")
    @Operation(summary = "删除角色",description = "通过ID删除角色")
    @OperateLog("删除角色")
    public ResultData delete(@PathVariable("id") String id){
        log.debug("删除角色：{}",id);
        if (id == null || !sysRoleService.exists(new LambdaQueryWrapper<SysRole>().eq(SysRole::getId,id))){
            return ResultData.fail("角色不存在");
        }
        //删除角色权限
        roleMenuService.deleteByRoleId(id);
        return sysRoleService.removeById(id)?ResultData.success():ResultData.fail(ReturnCodeEnum.RC500);
    }

    @GetMapping("/getByUserId/{id}")
    @Operation(summary = "通过用户ID查询角色",description = "通过用户ID查询角色")
    public ResultData getByUserId(@PathVariable("id") String id){
        log.debug("通过用户ID查询角色：{}",id);
        LambdaQueryWrapper<UserRole> lqw = new LambdaQueryWrapper<>();
        lqw.select(UserRole::getRoleId).eq(UserRole::getUserId,id);
        List<String> roleds = userRoleService.getBaseMapper().selectObjs(lqw);
        //查询出所有角色
        List<SysRole> sysRoles = sysRoleService.list();
        Map<String,Object> result = new HashMap<>();
        result.put("checkedIds",roleds);
        result.put("treeData",sysRoles);

        return ResultData.success(result);
    }

    @GetMapping("/getNoticeType")
    @Operation(summary = "获取通知类型",description = "获取通知类型")
    public ResultData getNoticeType(){
        return ResultData.success(NoticeType.values());
    }

    @GetMapping("/getRoleNotice/{id}")
    @Operation(summary = "获取角色通知",description = "获取角色通知")
    public ResultData getRoleNotice(@PathVariable("id") String id){
        log.debug("获取角色通知：{}",id);
        List<RoleNotice> roleNotices = roleNoticeService.getByRoleId(id);
        return ResultData.success(roleNotices);
    }

    @PostMapping("/saveNotice/{id}")
    @Operation(summary = "保存角色通知",description = "保存角色通知")
    @OperateLog("角色通知配置")
    public ResultData saveNotice( @RequestBody Integer[] noticeCodes,@PathVariable("id") String id){
       log.debug("保存角色通知：{}",id);
       log.debug("保存角色通知：{}",noticeCodes);
       if (StringUtils.isEmpty(id)){
           return ResultData.fail("角色不存在");
       }
       if(Objects.isNull(sysRoleService.getById(id))){
           return ResultData.fail("角色不存在");
       }
       if (roleNoticeService.addRoleNotice(id,noticeCodes)){
           return ResultData.success();
       }
        return ResultData.fail("配置失败");
    }


}
